package leetcode_tag.树;

import leetcode.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class LeetCode104 {

//    int max = 0;
//
//    public int maxDepth(TreeNode root) {
//        helper(root,0);
//        return max;
//    }
//
//    private void helper(TreeNode node, int level) {
//        if (node == null)
//            max = Math.max(max, level);
//        else {
//            helper(node.left, level + 1);
//            helper(node.right, level + 1);
//        }
//    }

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int leftHeight = maxDepth(root.left);
            int rightHeight = maxDepth(root.right);
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }

    public int maxDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            // 用size记录当前层数的个数，当前层遍历完后从下一层开始遍历
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            ans++;
        }
        return ans;
    }
}
